// ==UserScript==
// @name           Leprosorium karma attitude

// @description    Displays karma attitude of a user towardas you
// @include        http://leprosorium.ru/users/*
// @include        http://www.leprosorium.ru/users/*

// @exclude        
// ==/UserScript==

function get_obj_by_path(obj, path) {
	path = path;
	var routes = [];
	var step;
	var index;
	var parts = path.split(/\s+/);
	var j;
	for (var i = 0; i < parts.length; i++) {
		step = parts[i];
		index = 0;
		if (i == parts.length - 1) {
			routes[routes.length] = { step: step, index: index };
			break;
		}
		for (j = i + 1; j < parts.length; j++) {
			if (parts[j].search(/^\d+$/gi) == -1) {
				if (j == i + 1) {
					routes[routes.length] = { step: step, index: index };
				}
				break;
			} else {
				routes[routes.length] = { step: step, index: parts[j] }
			}
		}
		i = j - 1;
	}

	var result = obj;
	var route;
	try {
		for (var i = 0; i < routes.length && result; i++) {
			route = routes[i];
			with (route) {
				if (step == "parent") {
					while (index-- >= 0 && result) {
						result = result.parentNode;
					}
				} else if (step == "prev") {
					result = not_text_previous_subling(result, index);
				} else if (step == "next") {
					result = not_text_next_subling(result, index);
				} else if (step == "child") {
					result = not_text_child(result, index);
				} else if (step == "last") {
					result = not_text_last_child(result, index);
				} else if (step == "") {	//	do nothing, continue
				} else {
					alert("get_obj_by_path:\nUnknow step type:\"" + step + "\"");
				}
			}
		}
	} catch (e) {
		return null;
	}
	return result;
}

//	aliases
function not_text_child(obj, index) {
	return not_text_child_by_index(obj, index);
}
function not_text_last_child(obj, index) {
	return not_text_last_child_by_index(obj, index);
}
function not_text_next_subling(obj, index) {
	return not_text_next_subling_by_index(obj, index);
}
function not_text_previous_subling(obj, index) {
	return not_text_previous_subling_by_index(obj, index);
}

function not_text_child_length(obj) {
	var length = 0;
	var result = obj.firstChild;
	for (; result; result = result.nextSibling) {
		if (result.nodeType != 3 && result.nodeType != 8) length++;
	}
	return length;
}

function not_text_child_by_index(obj, index) {
	//	when damn mozilla gets white spaces it creates new node, while IE does not
	if (index == undefined) {
		index = 0;
	}
	var i = -1;
	var result = obj.firstChild;
	for (; result; result = result.nextSibling) {
		if (result.nodeType != 3 && result.nodeType != 8) i++;
		if (i == index) break;
	}
	return result;
}

function not_text_last_child_by_index(obj, index) {
	if (index == undefined) {
		index = 0;
	}
	var i = -1;
	var result = obj.lastChild;
	for (; result; result = result.previousSibling) {
		if (result.nodeType != 3 && result.nodeType != 8) i++;
		if (i == index) break;
	}
	return result;
}

function not_text_next_subling_by_index(obj, index) {
	if (index == undefined) {
		index = 0;
	}
	var i = -1;
	var result = obj.nextSibling;
	for (; result; result = result.nextSibling) {
		if (result.nodeType != 3 && result.nodeType != 8) i++;
		if (i == index) break;
	}
	return result;
}

function not_text_previous_subling_by_index(obj, index) {
	if (index == undefined) {
		index = 0;
	}
	var i = -1;
	var result = obj.previousSibling;
	for (; result; result = result.previousSibling) {
		if (result.nodeType != 3 && result.nodeType != 8) i++;
		if (i == index) break;
	}
	return result;
}

function get_my_login() {
	var greetings_div = document.getElementById("greetings");
	if (!greetings_div) {
		return false;
	}
	var a_list = greetings_div.getElementsByTagName("a");
	if (a_list.length < 2) {
		return false;
	}
	if (!a_list[0].firstChild) {
		return false;
	}
	return a_list[0].firstChild.nodeValue;
}

function get_my_id(user_id) {
	var my_cached_id = get_cookie("leprosorium_karma_attitude_user_id");
	if (my_cached_id) {
		get_my_id_callback(my_cached_id, user_id);
		return;
	}

	var my_login = get_my_login();
	if (my_login === false) {
		get_my_id_callback(false, user_id);
	}

	var xmlhttp = new XMLHttpRequest();
	xmlhttp.open("GET", get_base_url() + "/users/" + my_login, true);
	xmlhttp.onreadystatechange = function() {
		var ready = false;
		try {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				ready = true;
			}
		} catch (e) {
		}
		if (ready) {
			var result = xmlhttp.responseText.match(/<div\s+class\s*=\s*\"vote\"\s+uid\s*=\s*\"(\d+)\"\s*>/);
			if (result) {
				set_cookie("leprosorium_karma_attitude_user_id", result[1]);
				get_my_id_callback(result[1], user_id);
			} else {
				get_my_id_callback(false, user_id);
			}
		}
	};
	xmlhttp.send(null);
}

function get_user_id() {
	var main_div = document.getElementById("main_inner");
	if (!main_div) {
		return false;
	}
	var divs = main_div.getElementsByTagName("div");
	for (var i = 0; i < divs.length; i++) {
		if (divs[i].className == "vote") {
			if (divs[i].getAttribute("uid")) {
				return divs[i].getAttribute("uid");
			}
		}
	}
	return false;
}

function get_base_url() {
	return window.location.protocol + "//" + window.location.host;
}

function get_cookies() {
	var cookies_array = document.cookie.split(";");
	var cookies = {};
	for (var i = 0; i < cookies_array.length; i++) {
		var cookie_params = cookies_array[i].split("=");
		cookies[cookie_params[0]] = unescape(cookie_params[1]);
	}
	return cookies;
}

function set_cookie(name, value, expires) {
	var cookie = name + "=" + escape(value);
	if (expires != undefined) {
		cookie += ";expires=" + expires.toUTCString();
	}
	document.cookie = cookie;
}

function get_cookie(name) {
	return get_cookies()[name];
}

function get_gender() {
	var left_div = get_obj_by_path(document.getElementById("uservote"), "parent 3 prev");
	if (!left_div) {
		return;
	}
	var divs = left_div.getElementsByTagName("div");
	var registered_div = false;
	for (var i = 0; i < divs.length; i++) {
		if (divs[i].className == "userfriends") {
			registered_div = get_obj_by_path(divs[i], "child");
			break;
		}
	}
	if (!registered_div || registered_div.tagName.toLowerCase() != "div" || !registered_div.firstChild) {
		return false;
	}
	if (registered_div.firstChild.nodeValue.indexOf("Зарегистрирована") == -1) {
		return "m";
	} else {
		return "f";
	}
}

function get_statistics_div() {
	var statistics_div = get_obj_by_path(document.getElementById("uservote"), "parent 1 next");
	while (statistics_div && statistics_div.nodeType != 1) {
		statistics_div = statistics_div.nextSibling;
	}
	if (!statistics_div || statistics_div.tagName.toLowerCase() != "div") {
		return false;
	}
	return statistics_div;
}

function display_user_id(user_id) {
	var statistics_div = get_statistics_div();
	if (!statistics_div) {
		return;
	}

	var user_id_div = document.createElement("div");
	user_id_div.className = "userstat userrating";

	var text = "Номер " + user_id;
	user_id_div.appendChild(document.createTextNode(text));
	statistics_div.insertBefore(user_id_div, statistics_div.firstChild);
}

function set_attitude(attitude, gender) {
	var statistics_div = get_statistics_div();
	if (!statistics_div) {
		return;
	}

	var attitude_div = document.createElement("div");
	attitude_div.className = "userstat userrating";

	var text = "";
	if (gender == "m") {
		if (attitude === false || attitude === "0") {
			text += "Не покушался на вашу карму (0)";
		} else if (attitude == "-2") {
			text += "Насрал вам в карму (-2)";
		} else if (attitude == "-1") {
			text += "Насрал вам в карму (-1)";
		} else if (attitude == "1") {
			text += "Присунул вам в карму (+1)";
		} else if (attitude == "2") {
			text += "Присунул вам в карму (+2)";
		}
	} else {
		if (attitude === false || attitude === "0") {
			text += "Не покушалась на вашу карму (0)";
		} else if (attitude == "-2") {
			text += "Насрала вам в карму (-2)";
		} else if (attitude == "-1") {
			text += "Насрала вам в карму (-1)";
		} else if (attitude == "1") {
			text += "Присунула вам в карму (+1)";
		} else if (attitude == "2") {
			text += "Присунула вам в карму (+2)";
		}
	}
	attitude_div.appendChild(document.createTextNode(text));
	statistics_div.insertBefore(attitude_div, get_obj_by_path(statistics_div, "child 1"));
}

function process_attitude() {
	var user_id = get_user_id();
	display_user_id(user_id);
	get_my_id(user_id);
}

function get_my_id_callback(my_id, user_id) {
	if (!my_id) {
		return;
	}
	if (!user_id || user_id == my_id) {
		return;
	}

	var gender = get_gender();
	if (!gender) {
		return;
	}

	var xmlhttp = new XMLHttpRequest();
	xmlhttp.open("POST", get_base_url() + "/karmactl", true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange = function() {
		var ready = false;
		try {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				ready = true;
			}
		} catch (e) {
		}
		if (ready) {
			var response = false;
			try {
				eval("response = " + xmlhttp.responseText);
			} catch (e) {
			}
			if (!response) {
				return;
			}
			if (response.votes === undefined) {
				return;
			}
			var vote = false;
			for (var i = 0; i < response.votes.length; i++) {
				vote = response.votes[i];
				if (vote.uid == user_id) {
					break;
				}
			}
			var attitude = false;
			for (var i = 0; i < response.votes.length; i++) {
				var vote = response.votes[i];
				if (vote.uid == user_id) {
					attitude = vote.attitude;
					break;
				}
			}
			set_attitude(attitude, gender);
		}
	};
	xmlhttp.send("view=" + encodeURIComponent(my_id));
}

if (document.location.href.match('.ru/users/')) process_attitude();
